import { _getUserDetailById, _getUserInfo, _login } from "@/api/user"
import { getToken, removeToken, setTimeStamp, setToken } from "@/utils/auth"

const state = {
  token: getToken(), // 设置token为共享状态 初始化vuex的时候 就先从缓存中读取
  userInfo: {} // 这里定义一个空对象 为什么要定义空对象
}
const mutations = {
  setToken(state, token) {
    state.token = token // 将数据设置给vuex
    // 同步给缓存
    setToken(token)
  },
  removeToken(state) {
    state.token = null
    removeToken()
  },
  setUserInfo(state, result) {
    state.userInfo = result
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  async login({ commit }, data) {
    // 调用api接口
    const result = await _login(data) // 拿到token
    console.log(result)
    commit('setToken', result) // 设置token
    // 拿到token说明登录成功
    setTimeStamp() // 设置当前的时间戳
  },
  logout({ commit }) {
    commit('removeToken')
    commit('removeUserInfo')
  },
  async getUserInfo(context) {
    const result = await _getUserInfo()
    const baseInfo = await _getUserDetailById(result.userId)
    context.commit('setUserInfo', { ...result, ...baseInfo }) // 提交到mutations
    return result
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}